package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.MediaTypeConstant;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.ResourceInfo;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.entity.SubFileInfo;
import cn.stylefeng.guns.modular.business.enums.ResourceInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.enums.SubDrawInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.ResourceInfoMapper;
import cn.stylefeng.guns.modular.business.pojo.ResourceInfoRequest;
import cn.stylefeng.guns.modular.business.pojo.SubFileInfoRequest;
import cn.stylefeng.guns.modular.business.service.ResourceInfoService;
import cn.stylefeng.guns.modular.business.service.SubFileInfoService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现层
 *
 * @author zhangyaowen
 * @date 2021/09/13 15:11
 */
@Service
public class ResourceInfoServiceImpl extends ServiceImpl<ResourceInfoMapper, ResourceInfo> implements ResourceInfoService {

    @Resource
    private SubFileInfoService subFileInfoService;
    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(ResourceInfoRequest resourceInfoRequest) {
        ResourceInfo resourceInfo = new ResourceInfo();
        BeanUtil.copyProperties(resourceInfoRequest, resourceInfo);
        this.save(resourceInfo);
    }

    @Override
    public void del(ResourceInfoRequest resourceInfoRequest) {
        ResourceInfo resourceInfo = this.queryResourceInfo(resourceInfoRequest);
        this.removeById(resourceInfo.getId());
    }

    @Override
    public void edit(ResourceInfoRequest resourceInfoRequest) {
        ResourceInfo resourceInfo = this.queryResourceInfo(resourceInfoRequest);
        BeanUtil.copyProperties(resourceInfoRequest, resourceInfo);
        this.updateById(resourceInfo);
    }

    @Override
    public ResourceInfo detail(ResourceInfoRequest resourceInfoRequest) {
        return this.queryResourceInfo(resourceInfoRequest);
    }

    @Override
    public List<Map<String, Object>> findTuiJian() {
        LambdaQueryWrapper<ResourceInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long resourceType = 1l ;

        //Arrays.asList()
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceType), ResourceInfo::getResourceType, resourceType)
                    .orderByDesc(ResourceInfo::getResourceTime)
//        queryWrapper.orderByDesc(Boolean.parseBoolean("convert( resourceTime using gbk)"),ResourceInfo::getResourceTime) //格式需要注意
                .last(" limit 3 ;");
        List<ResourceInfo> list = this.list(queryWrapper);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(ResourceInfo resourceInfo : list){
            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(resourceInfo), Map.class);
            map.remove("id");
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            //map.remove("resourceContent");
            map.remove("resourceFile");
            map.remove("resourceType");

            String jmid = YunHeKey.YHZX+resourceInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return  mapList;
    }

    @Override
    public PageResult<Map<String, Object>> findPage(ResourceInfoRequest resourceInfoRequest) {
        LambdaQueryWrapper<ResourceInfo> queryWrapper = new LambdaQueryWrapper<>();

        String resourceName = resourceInfoRequest.getResourceName();
        String resourceFrom = resourceInfoRequest.getResourceFrom();

        queryWrapper.like(ObjectUtil.isNotEmpty(resourceName), ResourceInfo::getResourceName, resourceName);
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceFrom), ResourceInfo::getResourceFrom, resourceFrom).orderByDesc(ResourceInfo::getResourceTime);
        Page<ResourceInfo> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);
        PageResult<ResourceInfo> pageResult = PageResultFactory.createPageResult(sysRolePage);
        List<ResourceInfo> list = pageResult.getRows();
        PageResult<Map<String, Object>> mapPageResult = new PageResult<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(ResourceInfo resourceInfo : list){
            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(resourceInfo), Map.class);
            map.remove("id");
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            map.remove("resourceContent");
            map.remove("resourceFile");
            map.remove("resourceType");

            String jmid = YunHeKey.YHZX+resourceInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        mapPageResult.setRows(mapList);
        mapPageResult.setPageNo(pageResult.getPageNo());
        mapPageResult.setTotalRows(pageResult.getTotalRows());
        mapPageResult.setPageSize(pageResult.getPageSize());
        mapPageResult.setTotalPage(pageResult.getTotalPage());
        return  mapPageResult;
    }

    @Override
    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<ResourceInfo> wrapper = createWrapperByResource(riverList,townList,times,name);
        List<ResourceInfo>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(ResourceInfo resourceInfo:list) {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("title", resourceInfo.getResourceName());
            map.put("historyDating","");
            map.put("theCommon","");
            map.put("from",YunHeKey.ZIXUN);
            map.put("createTime", DateUtil.format(resourceInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.YHZX);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.YHZX+resourceInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<ResourceInfo> createWrapperByResource(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<ResourceInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), ResourceInfo::getResourceName, name).or()
                .like(ObjectUtil.isNotNull(name), ResourceInfo::getResourceFrom, name));

        return queryWrapper;
    }

    @Override
    public List<Map<String, Object>> toReview(String id) {
        byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(id, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YD后面真实的的id
        String name = StrUtil.subAfter(decryptStr,YunHeKey.YHZX,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid ;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(SubDrawInfoExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<ResourceInfo> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(name)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();
//            Map<String, Object> map =new HashMap<>();
//            map.put("error","id为空");
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(name), ResourceInfo::getId, name);
        List<ResourceInfo> resourceInfoList = this.list(queryWrapper);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ResourceInfo resourceInfo : resourceInfoList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(resourceInfo), Map.class);

            List<Map<String, Object>> mapLists = new ArrayList<>();

            String[] strings = StrUtil.splitToArray(resourceInfo.getResourceFile(),";");
            //String[] strings1 = new String[strings.length];
           // Long[] longs = new Long[strings.length];
            for( int i=0;i<strings.length;i++){
                Map<String, Object> mapOne = new HashMap<String, Object>();
                SubFileInfoRequest subFileInfoRequest = new SubFileInfoRequest();
                subFileInfoRequest.setFileOriginName(StrUtil.subBefore(strings[i],'.',false));
                subFileInfoRequest.setFileFirstBelong(YunHeKey.ZIXUN);
                PageResult<SubFileInfo> subFileInfoPageResult = subFileInfoService.findPageOne(subFileInfoRequest);
                if(!subFileInfoPageResult.getRows().isEmpty()) {

                   // longs[i]=subFileInfoPageResult.getRows().get(i).getId();
                    mapOne.put("fileId",subFileInfoPageResult.getRows().get(0).getId());
                    String suffix = subFileInfoPageResult.getRows().get(0).getFileSuffix();

                    String fileSuffix ="" ;
                    if(isPic(suffix)){
                        fileSuffix= "Pic-1";
                    }
                    if(isFile(suffix)){
                        fileSuffix= "File-2";
                    }
                    if(isVideo(suffix)){
                        fileSuffix= "Video-3";
                    }
                    //strings1[i]= fileSuffix;
                    mapOne.put("fileType",fileSuffix);
                    mapLists.add(mapOne);
                }
            }
            map.put("list",mapLists);

            mapList.add(map);
        }
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.ZIXUN,resourceInfoList.get(0).getResourceName(),userid,request);
        }

        return mapList;
    }


    @Override
    public List<ResourceInfo> findList(ResourceInfoRequest resourceInfoRequest) {
        LambdaQueryWrapper<ResourceInfo> wrapper = this.createWrapper(resourceInfoRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/09/13 15:11
     */
    private ResourceInfo queryResourceInfo(ResourceInfoRequest resourceInfoRequest) {
        ResourceInfo resourceInfo = this.getById(resourceInfoRequest.getId());
        if (ObjectUtil.isEmpty(resourceInfo)) {
            throw new ServiceException(ResourceInfoExceptionEnum.RESOURCEINFO_NOT_EXISTED);
        }
        return resourceInfo;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/09/13 15:11
     */
    private LambdaQueryWrapper<ResourceInfo> createWrapper(ResourceInfoRequest resourceInfoRequest) {
        LambdaQueryWrapper<ResourceInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long id = resourceInfoRequest.getId();
        String resourceName = resourceInfoRequest.getResourceName();
        String resourceContent = resourceInfoRequest.getResourceContent();
        String resourceFrom = resourceInfoRequest.getResourceFrom();
        String resourceTime = resourceInfoRequest.getResourceTime();
        Long resourceType = resourceInfoRequest.getResourceType();

        queryWrapper.eq(ObjectUtil.isNotNull(id), ResourceInfo::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceName), ResourceInfo::getResourceName, resourceName);
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceContent), ResourceInfo::getResourceContent, resourceContent);
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceFrom), ResourceInfo::getResourceFrom, resourceFrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(resourceTime), ResourceInfo::getResourceTime, resourceTime);
        queryWrapper.eq(ObjectUtil.isNotNull(resourceType), ResourceInfo::getResourceType, resourceType);

        return queryWrapper;
    }

    /**
     * 根据文件后缀判断是否图片
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isPic(String fileSuffix) {
        return MediaTypeConstant.IMG_JPG.equals(fileSuffix)
                || MediaTypeConstant.IMG_JPEG.equals(fileSuffix)
                || MediaTypeConstant.IMG_PNG.equals(fileSuffix)
                || MediaTypeConstant.IMG_GIF.equals(fileSuffix)
                || MediaTypeConstant.IMG_TIF.equals(fileSuffix)
                || MediaTypeConstant.IMG_BMP.equals(fileSuffix);
    }
    /**
     * 根据文件后缀判断是否文件
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isFile(String fileSuffix) {
        return MediaTypeConstant.FILE_DOC.equals(fileSuffix)
                || MediaTypeConstant.FILE_CSV.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOCM.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOCX.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOTM.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOT.equals(fileSuffix)
                || MediaTypeConstant.FILE_DOTX.equals(fileSuffix)
                || MediaTypeConstant.FILE_ET.equals(fileSuffix)
                || MediaTypeConstant.FILE_HTML.equals(fileSuffix)
                || MediaTypeConstant.FILE_PDF.equals(fileSuffix)
                || MediaTypeConstant.FILE_TXT.equals(fileSuffix)
                || MediaTypeConstant.FILE_WPS.equals(fileSuffix)
                || MediaTypeConstant.FILE_WPT.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLS.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLSX.equals(fileSuffix)
                || MediaTypeConstant.FILE_XLT.equals(fileSuffix);
    }
    /**
     * 根据文件后缀判断是否音视频
     *
     * @author xuyuxiang
     * @date 2020/7/6 15:31
     */
    public boolean isVideo(String fileSuffix) {
        return MediaTypeConstant.VIDEO_AVI.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_FLV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MKV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MOV.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MPEG.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MP3.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MP4.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_MPG.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_RM.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_RMVB.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_WMA.equals(fileSuffix)
                || MediaTypeConstant.VIDEO_WMV.equals(fileSuffix);
    }

}